package com.systop.ltbook.sms.statistics.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.systop.common.modules.security.user.model.User;
import com.systop.core.service.BaseGenericsManager;
import com.systop.core.util.DateUtil;
import com.systop.ltbook.sms.model.SmsSend;
import com.systop.ltbook.sms.statistics.util.Utils;

/**
 * 短息统计管理
 * @author DU
 */
@SuppressWarnings("unchecked")
@Service
public class SmsStatisticsManager extends BaseGenericsManager<SmsSend>{

	/**
	 * 短息发送统计，如果user为空，则统计所有已发短信
	 * @param beginDate 开始时间
	 * @param endDate 截至时间
	 * @param user 发送者，如果为空表示所以发送者
	 */
  public List<Map> statistics(Date beginDate, Date endDate, User user) {
		List<Map> rstList = new ArrayList();
		if (beginDate == null) {
			beginDate = new Date();
		}
		if (endDate == null) {
			endDate = new Date();
		}
		// 获得开始日期与结束日期时间段的月份
		List<String> months = Utils.getDateMonth(beginDate, endDate);
		int totalCount = 0;
		for (String month : months) {
			logger.debug("统计年月：{}", month);
			Date yearMonth = null;
			try {
				yearMonth = DateUtil.convertStringToDate("yyyy-MM", month);
				Date eDate = Utils.getLastDayOfMonth(yearMonth);
				Date sDate = Utils.getFirstDayOfMonth(yearMonth);
				StringBuffer hql = new StringBuffer("from SmsSend ss where 1=1 ");
				List args = new ArrayList();
				//该用户发送的短信，如果为空则统计所有已发短信
				if (user != null) {
					hql.append(" and ss.sender.id = ?");
					args.add(user.getId());
				}
				if (sDate != null && eDate != null) {
					hql.append(" and ss.sendTime between ? and ?");
					args.add(sDate);
					args.add(eDate);
				}
				List<SmsSend> smsRst = getDao().query(hql.toString(), args.toArray());
				int sendCount = 0;
				Map rstMap = new HashMap();
				for (SmsSend sms : smsRst) {
					sendCount += sms.getSmsNums();
				}
				rstMap.put("month", month);
				rstMap.put("sendCount", sendCount);
				totalCount += sendCount;
				
				rstList.add(rstMap);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		logger.debug("发送短信总条数是：{}", totalCount);
		return rstList;
	}
}
